package com.pat.java.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.commons.lang.StringUtils;

/**
 * @author Administrator
 * 
 */
public class ReadExcelTool {
	
	public static ReadExcelTool instance = new ReadExcelTool();

	/**
	 * 2003 excel 读取数据方式
	 * @param filePath
	 * @param sheetNum
	 * @return
	 */
	public static List<Map<String, String>> readExcelFile(String filePath,	int sheetNum) {
		List<Map<String, String>> ls = new ArrayList<Map<String, String>>();
		Workbook book = null;
		try { // 读Excel文件
			book = Workbook.getWorkbook(new File(filePath)); // 获得工作表个数 Sheet
			Sheet sheet = book.getSheet(sheetNum);
			for (int i = 0; i < sheet.getRows(); i++) { // 获得行
				Cell[] row = sheet.getRow(i);
				Map<String, String> rowMap = new HashMap<String, String>();
				for (int j = 0; j < row.length; j++) {
					// 获得单元格内容 
					String content=row[j].getContents();
					if (StringUtils.isNotBlank(content)) { // 因为从0开始,所以要+1
						rowMap.put(String.valueOf(j + 1), content);
					}
				}
				if (!rowMap.isEmpty()) {
					ls.add(rowMap);
				}
			}
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (book != null) {
				book.close();
			}
		}
		return ls;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// readExcelFile("C:/Users/Administrator/Desktop/三国/怪物属性数值需求.xlsx",3);
		
		/*
		 * 2010 excel 读取数据方式
		 */
		File file = new File("C:/Users/Administrator/Desktop/三国/怪物属性数值需求.xlsx");
		Excel2010Operation excel = new Excel2010Operation();
		List<List<String[]>> workBook;
		try {
			workBook = excel.getData(file, "all", 0);
			for (List<String[]> sheet : workBook) {
				for (String[] row : sheet) {
					for (int col = 0; col < row.length; col++) {
						System.out.print(row[col] + "\t");
					}
					System.out.println();
				}

				System.out.println();
				System.out.println("……………… one sheet read end …………………………………");
				System.out.println();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}